package com.kaibes.im.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ImageSpan;

public class FaceUtil {

    public static SpannableStringBuilder showMessageFace(Context context,
	    String message, float scale) {
	Matrix matrix = new Matrix();
	matrix.postScale(scale, scale);

	SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(
		message);
	// 过滤和表情相关的字符串以用于转换成图片
	Pattern pattern = Pattern.compile("#\\([^#(]+\\)");
	Matcher matcher = pattern.matcher(message);

	while (matcher.find()) {
	    // 分为三组(#\\()，([^)]+)。(\\))，取第2组 
	    String face = matcher.group()
		    .replaceAll("(#\\()([^)]+)(\\))", "$2");
	    Bitmap bitmap = BitmapFactory.decodeResource(
		    context.getResources(),
		    StaticValuesUtil.FACE_HACE_CLASSIC.get(face));
	    Bitmap resizeBmp = Bitmap.createBitmap(bitmap, 0, 0,
		    bitmap.getWidth(), bitmap.getHeight(), matrix, true);
	    ImageSpan imageSpan = new ImageSpan(context, resizeBmp);
	    spannableStringBuilder.setSpan(imageSpan, matcher.start(),
		    matcher.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
	}
	return spannableStringBuilder;
    }

    public static SpannableStringBuilder showMessageFace(Context context,
	    String message) {
	return showMessageFace(context, message, 1.0f);
    }
}
